import datetime
import json
import talib

import numpy as np
import os

import baostock as bs
import pandas as pd

# Create your views here.
from django.db.models import Count
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from yaml import serialize

from chartstest.datasViews import connectushare
from chartstest.models import TusharDate, DealDetail, stock_basic, cctv_news
import tushare as ts


def cctvNewsIndex(request):
    data_list = []
    # query = TusharDate.objects.all().query
    # query.group_by = ['tscode']
    # book_list = QuerySet(query=query, model=TusharDate)
    # tscode 分组
    result = TusharDate.objects.values('tscode').annotate(Count=Count('tscode')).order_by('-id')[:3]
    # print(type(result))
    # print(result.count())

    for obj in result:
        # print(obj)
        data_list.append(obj)

    # for i in range(0, len(book_list)):
    #     #data_list.append(book_list[i][9])
    #     print(i)
    # print(book_list.count())

    # print("json:" + json.dumps(data_list))
    # print(data_list)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'baostock/downdataIndex.html', {"dataList": json.dumps(data_list, ensure_ascii=False)})


# 在处理函数加此装饰器即可
@csrf_exempt
def cctvNewsDate(request):
    # 从tushare查询某只股票日线数据
    # pro = connectushare
    # 查询当前所有正常上市交易的股票列表
    pro = ts.pro_api('09c23ca7df4d6e0692459fd98de6207c1d687158fb1e946f5be77af8')

    pd.set_option('display.max_columns', None)

    begin = datetime.date(2017, 1, 21)
    end = datetime.date(2019, 4, 7)
    for i in range((end - begin).days + 1):
        day = begin + datetime.timedelta(days=i)

        datas = pro.cctv_news(date=day.strftime('%Y%m%d'))
        # 将date值转换为datetime类型，并且设置成index
        datas.index = datas.date

        # dataform 转成list
        train_data = np.array(datas)  # np.ndarray()
        train_x_list = train_data.tolist()  # list

        # 数据排序，正序
        train_x_list.sort(key=lambda x: x[0], reverse=True)

        for i in range(1, len(train_x_list)):
            print("时间:" + train_x_list[i][0])
            print("标题:" + train_x_list[i][1])
            s = cctv_news()
            s.date = train_x_list[i][0]
            s.title = train_x_list[i][1]
            s.content = train_x_list[i][2]

            s.save()

        print(str(day.strftime('%Y%m%d')))

    return HttpResponse(json.dumps(datas, ensure_ascii=False), content_type="application/json,charset=utf-8")


# 在处理函数加此装饰器即可
@csrf_exempt
def jsonDate(request):
    tscode = request.POST['tscode']
    tusharDates = TusharDate.objects.filter(tscode=tscode)
    # print(tusharDates)

    # ret = models.TusharDate.objects.all().order_by("dayIncome", "id")
    ret1 = serialize("json", tusharDates)
    retList = json.loads(ret1)
    # print(retList)
    ret2 = []
    print('---------------------')
    for num in range(len(retList)):
        fields = retList[num]['fields']
        fields.update(id=retList[num]['pk'])
        ret2.append(fields)
        # print(ret2)

    data = {'status': 0, 'dates': ret2}
    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")


# 计算查询结果
# 在处理函数加此装饰器即可
@csrf_exempt
def downdataResult(request):
    # 参数
    buy = 0
    sell = 0
    tscode = ''
    startTime = ''
    endTime = ''
    tscode = request.POST['tscode']
    startTime = request.POST['startTime']
    endTime = request.POST['endTime']
    macdF = request.POST['macdF']
    macdSL = request.POST['macdSL']
    macdSI = request.POST['macdSI']
    buy = request.POST['buy']
    sell = request.POST['sell']
    #
    ls = json.dumps(tscode, ensure_ascii=False)
    info = HttpResponse(ls)

    # 下面这两行设置夸域请求，跨域就是用这两行
    # info['Access-Control-Allow-Origin'] = '*'
    # info['Access-Control-Allow-Headers'] = "Content-Type"
    if tscode == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    if startTime == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    if endTime == '':
        ls = json.dumps(tscode, ensure_ascii=False)
        info = HttpResponse(ls)
        return info
    startTime = startTime.replace('-', '')
    endTime = endTime.replace('-', '')
    print(startTime + endTime)
    # pro = ts.pro_api('09c23ca7df4d6e0692459fd98de6207c1d687158fb1e946f5be77af8')

    # 使用ggplot样式，好看些
    # mpl..style.use("ggplot")
    # 获取上证指数数据
    # data = ts.get_k_data("000001", index=True, start="2019-01-01")
    ts_code = '600575.SH'
    start_date = '20180701'
    end_date = '20191024'
    f = 12
    s = 26
    si = 9
    #
    if macdF != '':
        f = int(macdF)
    if macdSL != '':
        s = int(macdSL)

    if macdSI != '':
        si = int(macdSI)

    #### 登陆系统 ####
    lg = bs.login()
    # 显示登陆返回信息
    print('login respond error_code:' + lg.error_code)
    print('login respond  error_msg:' + lg.error_msg)

    # date  交易所行情日期
    # code 证券代码
    # open 开盘价
    # high 最高价
    # low 最低价
    # close 收盘价
    # preclose 前收盘价
    # volume 成交量（累计 单位：股）
    # amount 成交额（单位：人民币元）
    # adjustflag 复权状态(1：后复权， 2：前复权，3：不复权）
    # turn 换手率 [指定交易日的成交量(股 ) /指定交易日的股票的流通股总股数(股) ] *10 0%       tradestatus 	交易状态(1：正常交易 0：停牌）
    # pctChg 	涨跌幅（百分比） 	日涨跌 幅 =[(指定交易日的收盘 价 -指定交易日前收盘价 ) /指定交易日前收盘价 ] *10 0%
    #                            peTTM 	滚动市盈率 	(指定交易日的股票收盘 价 /指定交易日的每股盈余TTM ) =(指定交易日的股票收盘 价 *截至当日公司总股本 ) /归属母公司股东净利润TTM
    # pbMRQ 	市净率 	(指定交易日的股票收盘 价 /指定交易日的每股净资产 ) =总市 值 /(最近披露的归属母公司股东的权 益 -其他权益工具)
    # psTTM 	滚动市销率 	(指定交易日的股票收盘 价 /指定交易日的每股销售额 ) =(指定交易日的股票收盘 价 *截至当日公司总股本 ) /营业总收入TTM
    # pcfNcfTTM 	滚动市现率 	(指定交易日的股票收盘 价 /指定交易日的每股现金流TTM ) =(指定交易日的股票收盘 价 *截至当日公司总股本 ) /现金以及现金等价物净增加额TTM
    # isST 	是否ST股，1是，0否

    #### 获取历史K线数据 ####
    # 详细指标参数，参见“历史行情指标参数”章节
    rs = bs.query_history_k_data_plus(tscode,
                                      "date,code,open,high,low,close,preclose,volume,amount,adjustflag,turn,tradestatus,pctChg,peTTM,pbMRQ,psTTM,pcfNcfTTM,isST",
                                      start_date=startTime, end_date=endTime,
                                      frequency="d", adjustflag="3")  # frequency="d"取日k线，adjustflag="3"默认不复权
    print('query_history_k_data_plus respond error_code:' + rs.error_code)
    print('query_history_k_data_plus respond  error_msg:' + rs.error_msg)
    pd.set_option('display.max_columns', None)

    data = rs.data
    # macd（对应diff），
    # macdsignal（对应dea），
    # macdhist（对应macd）。
    data["DIFF"], data["DEA"], data["MACD"] = talib.MACD(data.close, fastperiod=f, slowperiod=s, signalperiod=si)
    # dataform 转成list
    train_data = np.array(data)  # np.ndarray()
    train_x_list = train_data.tolist()  # list
    #### 打印结果集 ####

    for i in range(1, len(train_x_list)):
        print("数据开始---------------")
        print(train_x_list[i][1])

    data_list = []
    while (rs.error_code == '0') & rs.next():
        # 获取一条记录，将记录合并在一起
        data_list.append(rs.get_row_data())
    result = pd.DataFrame(data_list, columns=rs.fields)
    #### 结果集输出到csv文件 ####
    result.to_csv("D:/history_k_data.csv", encoding="gbk", index=False)
    print(result)

    # 计算RSI
    # data["rsi"] = talib.RSI(data.close)

    # 计算MACD指标数据
    # data["macd"], data["sigal"], data["hist"] = talib.MACD(data.close)

    # def OnKeyTyped(self, event):
    #          print(event.GetString())

    # dataform 转成list
    train_data = np.array(rs)  # np.ndarray()
    train_x_list = train_data.tolist()  # list

    # 数据排序，正序
    # train_x_list.sort(key=lambda x: x[0], reverse=True)
    # print(train_x_list)
    # 买点
    bu = 0
    # 卖点
    se = 0

    #       buy,sell
    if buy != '':
        bu = int(buy)
    if sell != '':
        se = int(sell)

    total = 0
    a = 0
    b = 0
    buyPrice = 0.00
    sellPrice = 0.00
    success_ratio = 0.00
    buyTime = ""
    sellTime = ""

    dealDetailList = []
    # ts_code 股票代码 0
    # trade_date 交易日期 1
    # open 开盘价 2
    # high 最高价 3
    # low 最低价 4
    # close 收盘价 5
    # pre_close 昨收价 6
    # change 涨跌额 7
    # pct_chg 涨跌幅 8
    # vol 成交量 （手）9
    # amount 成交额 （千元） 10
    # DIFF 11
    # DEA 12
    # MACD 13
    # ma10  14
    # ma30  15
    #
    ma = 1

    if bu > 0:
        ma = bu

    if se > ma:
        ma = se
    print(ma)
    openPrice = 0.00
    # 获取3天的数据：开盘价，收盘价，diff，dea，
    for i in range(1, len(train_x_list) - ma):
        result = 0.00

        # 前一天的数据
        open2 = train_x_list[i - 1][2]
        DIFF2 = float(train_x_list[i - 1][11])
        DEA2 = float(train_x_list[i - 1][12])
        MACD2 = float(train_x_list[i - 1][13])
        close2 = train_x_list[i - 1][5]
        # print(train_x_list[i])

        # 当天数据
        # 开盘价
        open = train_x_list[i][2]
        close = train_x_list[i][5]
        # 均价
        avg = train_x_list[i][4]
        #
        DIFF = float(train_x_list[i][11])
        DEA = float(train_x_list[i][12])
        MACD = float(train_x_list[i][13])
        # 收盘价

        # 后一天数据
        open3 = train_x_list[i + 1][2]
        DIFF3 = float(train_x_list[i + 1][11])
        DEA3 = float(train_x_list[i + 1][12])
        MACD3 = float(train_x_list[i + 1][13])
        close3 = train_x_list[i + 1][5]

        # 有空值循环下一个
        if DIFF2 != DIFF2:
            continue

        # 实现DIFF、DEA均为正，DIFF向上突破DEA，买入股票；
        # DIFF、DEA均为负，DIFF向下突破DEA，卖出股票
        # DIFF DEA 买点 交叉点判断，前一天数值DIFF的值大于DEA2，后一天数据DIFF小于DEA
        # 当天相等，后一天的DIFF2>DEA2,这一天作为金叉点
        # if (DIFF == DEA and DIFF3 > DEA3):
        #     # buy=open
        #     # 买入时间
        #     buyTime = train_x_list[i + bu][1]
        #     # 买入价格
        #     buyPrice = float(train_x_list[i + bu][2])
        #     #第一个买价
        #     if (openPrice == 0.00):
        #         openPrice = buyPrice
        #     print("买入开始---------------")
        #     print(
        #         "DIFF:" + str(DIFF)[0:5] + " DEA:" + str(DEA)[0:5] + " DIFF2:" + str(DIFF2)[0:5] + " DEA2:" + str(DEA2)[
        #                                                                                                       0:5])
        #     print(buyTime)
        #     print(buyPrice)
        #     print("买入结束---------------")
        #
        #     continue
        # elif (DIFF3 > DEA3 and (DIFF2 < DEA2 or DIFF == DEA)):
        # 如果当前有余额，并且DIFF、DEA均为正，DIFF向上突破DEA
        if DIFF > 0 and DEA > 0 and DIFF2 > DEA2 and DIFF3 < DEA3:
            # if (MACD2 <= 0 and MACD >= 0 and MACD3>=0):

            # buy=open
            # 买入时间
            buyTime = train_x_list[i + bu][1]
            # 买入价格
            buyPrice = float(train_x_list[i + bu][2])
            # 第一个买价
            if (openPrice == 0.00):
                openPrice = buyPrice
            # print("买点：buy" + str(buyPrice) + "第" + str(train_x_list[i + bu][1]))
            print("买入开始---------------")
            print("DIFF3:" + str(DIFF3)[0:5] + " DEA3:" + str(DEA3)[0:5] + " DIFF2:" + str(DIFF2)[0:5] + " DEA2:" + str(
                DEA2)[0:5] + "DIFF:" + str(DIFF)[0:5] + "DEA:" + str(DEA)[0:5] + "MACD:" + str(MACD)[0:5])
            print(buyTime)
            print(buyPrice)
            print("买入结束---------------")
            continue

        # DIFF DEA 卖点  交叉点判断，前一天数值DIFF的值小于DEA2，后一天数据DIFF大于DEA
        # if (DIFF == DEA and DIFF3 < DEA3):
        #     # sell=open
        #     # 卖出时间
        #     sellTime = train_x_list[i + se][1]
        #     # 卖出价格
        #     sellPrice = float(train_x_list[i + se][2])
        #     print("卖出开始---------------")
        #     print(
        #         "DIFF:" + str(DIFF)[0:5] + " DEA:" + str(DEA)[0:5] + " DIFF2:" + str(DIFF2)[0:5] + " DEA2:" + str(DEA2)[
        #                                                                                                       0:5])
        #     print(sellTime)
        #     print(sellPrice)
        #     print("卖出结束---------------")
        # 如果DIFF、DEA均为负，DIFF向下跌破DEA，并且目前有头寸
        if DIFF < 0 and DEA < 0 and DIFF2 < DEA2 and DIFF3 > DEA3:
            # if (MACD3 < 0 and MACD <= 0 and MACD2 >= 0):
            # sell=open
            # 卖出时间
            sellTime = train_x_list[i + se][1]
            # 卖出价格
            sellPrice = float(train_x_list[i + se][2])
            print("卖出开始---------------")
            print("DIFF3:" + str(DIFF3)[0:5] + " DEA3:" + str(DEA3)[0:5] + " DIFF2:" + str(DIFF2)[0:5] + " DEA2:" + str(
                DEA2)[0:5] + "DIFF:" + str(DIFF)[0:5] + "DEA:" + str(DEA)[0:5] + "MACD:" + str(MACD)[0:5])
            print(sellTime)
            print(sellPrice)
            print("卖出结束---------------")

            # 计算一次交易，清零参数
        if (buyPrice != 0.00 and sellPrice != 0.00):
            result = sellPrice - buyPrice
            if (result > 0):
                b = b + 1

            print("买入价格：" + str(buyPrice) + "买入时间：" + str(buyTime) + "卖出价格：" + str(sellPrice) + "卖出时间：" + str(
                sellTime) + "" + "盈利：" + str(result))

            a = a + 1
            # 添加交易详细信息表
            dealDetail = DealDetail()
            dealDetail.tscode = tscode
            dealDetail.buyTime = buyTime
            dealDetail.sellTime = sellTime
            dealDetail.buyPrice = buyPrice
            dealDetail.sellPrice = sellPrice
            dealDetail.tradProfit = round(result, 3)
            dealDetail.profitability = round((result / buyPrice) * 100, 3)
            dealDetailList.append(dealDetail)
            # tusharDate.dealdetail_set.add(dealDetail)

            buyPrice = 0.00
            sellPrice = 0.00
            buyTime = ''
            sellTime = ''
        elif (buyPrice == 0.00 and sellPrice != 0.00):
            buyPrice = 0.00
            sellPrice = 0.00
            buyTime = ''
            sellTime = ''

        total = total + result
        if (a != 0):
            success_ratio = round((b / a) * 100, 3)

    tusharDate = TusharDate()
    tusharDate.tscode = tscode
    tusharDate.macdF = f
    tusharDate.macdSI = s
    tusharDate.macdSL = si
    tusharDate.startTime = startTime
    tusharDate.endTime = endTime
    tusharDate.buy = buy
    tusharDate.sell = sell
    tusharDate.tradProfit = round(total, 3)
    tusharDate.successRatio = success_ratio
    tusharDate.profitability = round((total / openPrice) * 100, 3)

    if tusharDate:
        # print(tusharDate.successRatio)
        tusharDate.save()
        for i in range(0, len(dealDetailList)):
            dealDetail = dealDetailList[i]
            dealDetail.tusharDate_id = tusharDate.id
            dealDetail.save()

    #  将数据写入新文件
    result_list = np.array(rs)
    # columns = ["ts_code", "star_date", "end_date", "macdF", "macdSl", "macdSI", "buy", "sell", "total",
    #            "success_ratio"]
    # dt = pd.DataFrame(result_list, columns=columns)
    dt = pd.DataFrame(result_list)
    # dt.to_excel("result_xlsx.xlsx", index=0)
    # dt.to_csv("result_csv.csv", index=0)
    # print(tscode)
    dt.to_csv(str(tusharDate.id) + '.csv', mode='a', header=0, index=0, float_format='%.2f')
    return info


# 详细信息
@csrf_exempt
def downdataDetail(request):
    print("--------------------------------------详细信息")
    # 参数
    id = request.GET['id']
    data_list = []
    result = DealDetail.objects.filter(tusharDate_id=id)

    ret1 = serialize("json", result)
    retList = json.loads(ret1)
    # print(retList)

    for num in range(len(retList)):
        fields = retList[num]['fields']

        fields.update(id=retList[num]['pk'])
        data_list.append(fields)
        # print(ret2)

    tusharDate_id = data_list[0]['tusharDate']

    # print("tscode:" + json.dumps(tscode))

    # 读取文件数据
    data = pd.read_csv(str(tusharDate_id) + '.csv')
    train_data = np.array(data)  # np.ndarray()
    macdlist = train_data.tolist()  # list
    macdlist.sort()
    # print(macdlist)
    # print(type(macdlist))

    # ret1 = serialize("json", datelist)
    # retList = json.loads(ret1)
    # # print(retList)
    # ret2 = []
    # print('---------------------')
    # for num in range(len(retList)):
    #     print(retList[num])
    #
    #     ret2.append(fields)
    #     # print(ret2)

    aaaalist = json.dumps(macdlist, ensure_ascii=False)
    # print(aaaalist)

    # return render(request, 'chartstest/public.html', {"dataList": data_list})
    return render(request, 'chartstest/macdDetails.html', {"detailList": json.dumps(data_list, ensure_ascii=False),
                                                           "macdlist": aaaalist})


# 在处理函数加此装饰器即可
@csrf_exempt
def delDate(request):
    tscode = request.POST['tscode']

    tusharDates = TusharDate.objects.filter(tscode=tscode)
    # print(tusharDates)

    for obj in tusharDates:
        url = str(obj.id) + ".csv"
        if os.path.isfile(url):
            os.remove(url)
        print(obj.id)

    DealDetail.objects.filter(tscode=tscode).delete()

    TusharDate.objects.filter(tscode=tscode).delete()
    # ret = models.TusharDate.objects.all().order_by("dayIncome", "id")

    data = {'status': 0, 'message': '删除成功！'}
    return HttpResponse(json.dumps(data, ensure_ascii=False), content_type="application/json,charset=utf-8")
